package com.jdy.haoduoai.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.AddTeacherListActivity;
import com.jdy.haoduoai.activity.BabyCalenderActivity;
import com.jdy.haoduoai.activity.BabyKaraokeActivity;
import com.jdy.haoduoai.activity.BabyPhotoCloudActivity;
import com.jdy.haoduoai.activity.BabyTellStoryActivity;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.activity.BreathLightActivity;
import com.jdy.haoduoai.activity.DevicePropertyActivity;
import com.jdy.haoduoai.activity.LoginActivity;
import com.jdy.haoduoai.activity.MembershipCenterActivity;
import com.jdy.haoduoai.activity.MyLoveListActivity;
import com.jdy.haoduoai.activity.MyVoiceActivity;
import com.jdy.haoduoai.activity.PersonalInformationActivity2;
import com.jdy.haoduoai.activity.RecentPlayActivity;
import com.jdy.haoduoai.activity.SchoolAlbumActivity;
import com.jdy.haoduoai.activity.SettingActivity;
import com.jdy.haoduoai.activity.WebViewContainerActivity;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.model.ImUserSig;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeSysMessage;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.CircularImageView;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.scrollview.OnScrollChangedCallback;
import com.jdy.haoduoai.view.visualizer.FrequencyDistributionBarView;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

//import com.jdy.haoduoai.intface.IAsyncTask;
//import com.jdy.haoduoai.intface.IMParseListener;

/**
 * 个人中心
 *
 * @author hf
 */
public class TabMineFragment extends BaseFragment implements OnClickListener,
        OnScrollChangedCallback, OnDataReceivedListener, DeviceStateListener {

    private static final String TAG = TabMineFragment.class.getSimpleName();

    @InjectView(id = R.id.Myvoice, click = true)
    private RelativeLayout Myvoicelyt;
    @InjectView(id = R.id.Mylove, click = true)
    private LinearLayout Mylovelyt;
    //  @InjectView(id = R.id.Mymessage, click = true)
//  private LinearLayout Mymessagelyt;
    @InjectView(id = R.id.home_face_img, click = true)
    private CircularImageView mHomeFaceImageView;
    @InjectView(id = R.id.parentAccountIdTextView)
    private TextView username;
    @InjectView(id = R.id.expired_at_textview)
    private TextView expired_at_textview;
    @InjectView(id = R.id.scoreCenterLinearLayout, click = true)
    private View scoreCenterLinearLayout; // 积分商城
    @InjectView(id = R.id.playHistoryLinearLayout, click = true)
    private View playHistoryLinearLayout; // 播放记录
    @InjectView(id = R.id.Mytopic, click = true)
    private View Mytopic; // 我的话题
    //  @InjectView(id = R.id.MyDownloaded, click = true)
//  private View MyDownloaded;
    @InjectView(id = R.id.rel_babykalaok, click = true)
    private View rel_babykalaok;
    @InjectView(id = R.id.rel_babytellstory, click = true)
    private View rel_babytellstory;
    @InjectView(id = R.id.rel_babycloudalbum, click = true)
    private View rel_babycloudalbum;
    @InjectView(id = R.id.rel_schoolalbum, click = true)
    private View rel_schoolalbum; // 校园相册

    @InjectView(id = R.id.rel_babyteacher, click = true)
    private View rel_babyteacher; // 宝宝老师

    @InjectView(id = R.id.tv_name, click = true)
    private TextView tv_name;
    @InjectView(id = R.id.tv_score, click = true)
    private TextView tv_score;
    @InjectView(id = R.id.device_stateview, click = true)
    private FrequencyDistributionBarView device_stateview;
    @InjectView(id = R.id.membershipPackageIntroLinearLayout, click = true)
    private View membershipPackageIntroLinearLayout;
    @InjectView(id = R.id.exitRippleView)
    private RippleView mExitRippleView;
    @InjectView(id = R.id.img_vip)
    private ImageView img_vip;
    @InjectView(id = R.id.img_setting, click = true)
    private ImageView img_setting;
    @InjectView(id = R.id.view_mydevice, click = true)
    private View view_mydevice;

    //宝宝故事机
    @InjectView(id = R.id.rel_story_baby, click = true)
    private RelativeLayout rl_story_baby;


    @InjectView(id = R.id.exitImg, click = true)
    private RelativeLayout exitImg;

    private TextView tv_levelRank;

    private LeUser mLeUser;
    private Bitmap mScaleCrop;

    private ImUserSig mUserSigWrapper;
    private BroadcastReceiver mReceiver = null;

    private List<LeSysMessage> mSysMessageList;
    @SuppressWarnings("unused")
    private BaseActivity mBaseActivity;

    @InjectView(id = R.id.profile_scrollview)
    private com.jdy.haoduoai.view.scrollview.ObservableScrollView mScrollView;

    @InjectView(id = R.id.profile_head_img)
    private ImageView mHeadImg;

    private void bindService() {

        if (SocketThreadManager.getInstance() != null) {
            SocketThreadManager.getInstance().setDeviceStateListener(
                    TabMineFragment.this);
            SocketThreadManager.getInstance().requestDeviceDetails();

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
        }
    };

    @SuppressLint("ValidFragment")
    public TabMineFragment(BaseActivity ba) {
        mBaseActivity = ba;
    }

    public TabMineFragment() {
    }

    @Override
    public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
                             ViewGroup container) {
        View bodyView = LayoutInflater.from(mContext).inflate(
                R.layout.profile_layout, container, false);

        tv_levelRank = (TextView) bodyView.findViewById(R.id.tv_levelRank);

        return bodyView;
    }

//  private ImHelper mImHelper;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();

        if (mLeUser == null) {
            mLeUser = Tools.restoreLeUser();
            if (mLeUser == null) {
                Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        }

        getViews();
        bindService();

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if ("updateparentheadimage".equals(action)) {
                    SharedPreferences prefs = mContext.getSharedPreferences(
                            Constant.USER_INFO, Context.MODE_PRIVATE);

                    String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
                    if (Tools.isNotEmpty(parentImagePath)) {
                        Uri parentUri = Uri.parse(parentImagePath);

                        Bitmap originalBitmap = ImageUtils.getBitmapFromUri(mContext,
                                parentUri);
                        if (originalBitmap != null) {
                            mScaleCrop = ImageUtils.scaleCropToFit(originalBitmap, 300, 300,
                                    true);
                        }

                        mHomeFaceImageView.setImageURI(null);
                        if (mScaleCrop != null)
                            mHomeFaceImageView.setImageBitmap(mScaleCrop);
                    } else if (Tools.isEmpty(parentImagePath) && mLeUser != null) {
                        getHeadImage(mLeUser.avatar);
                    } else if (Tools.isEmpty(parentImagePath) && mLeUser == null) {
                        img_vip.setImageResource(R.drawable.diamond_gray);
                    }
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction("updateparentheadimage");
        mContext.registerReceiver(mReceiver, filter);
    }

    private void initView() {
        if (LeConfig.isDeviceActivated && Tools.isNotEmpty(LeConfig.expiredAt)) {
            int index = LeConfig.expiredAt.indexOf(" ");
            expired_at_textview.setText(LeConfig.expiredAt.subSequence(0, index)
                    + " 到期");
        } else {
            expired_at_textview.setText("开通会员，尊享特权");
        }

        mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();

        if (mLeUser != null) {
            if (Tools.isNullStr(mLeUser.machine)) {
                username.setText("用户" + String.valueOf(mLeUser.id));
            } else if (Tools.isNotNullStr(mLeUser.machine)) {
                username.setText(mLeUser.machine.name + "的" + mLeUser.callname);
            } else {
                username.setText(mLeUser.nickname);
            }
        }
    }

    private void getViews() {
        if (Tools.isNotEmpty(mLeUser) && Tools.isNotEmpty(mLeUser.profile)) {
            tv_levelRank.setText("Lv" + mLeUser.profile.rank);
            tv_score.setText("积分" + mLeUser.profile.score);
        }

        img_setting.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
        mScrollView.setOnScrollChangedCallback(this);
        mExitRippleView
                .setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
                    @Override
                    public void onComplete(RippleView rippleView) {
                        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
                                getActivity()).setMessage("确定要退出当前账号？")
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                })
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        doExitApp();
                                    }
                                });

                        if (!getActivity().isFinishing()) {
                            cdb.create().show();
                        }
                    }
                });
    }

    private void setUserAvatar() {
        if (img_vip == null) {
            return;
        }

        initView();

        if (LeConfig.isDeviceActivated) {
            img_vip.setImageResource(R.drawable.diamond);
        } else {
            img_vip.setImageResource(R.drawable.diamond_gray);
        }

        SharedPreferences prefs = mContext.getSharedPreferences(Constant.USER_INFO,
                Context.MODE_PRIVATE);

        String parentImagePath = prefs.getString(Constant.PARENT_AVATAR, "");
        if (Tools.isNotEmpty(parentImagePath)) {
            Uri parentUri = Uri.parse(parentImagePath);

            if (mScaleCrop == null) {
                Bitmap originalBitmap = ImageUtils
                        .getBitmapFromUri(mContext, parentUri);
                if (originalBitmap != null) {
                    mScaleCrop = ImageUtils
                            .scaleCropToFit(originalBitmap, 300, 300, true);
                }
            }

            mHomeFaceImageView.setImageURI(null);
            if (mScaleCrop != null)
                mHomeFaceImageView.setImageBitmap(mScaleCrop);
            img_vip.setImageResource(R.drawable.diamond);
        } else if (Tools.isEmpty(parentImagePath) && mLeUser != null) {
            getHeadImage(mLeUser.avatar);
        } else if (Tools.isEmpty(parentImagePath) && mLeUser == null) {
            img_vip.setImageResource(R.drawable.diamond_gray);
        }
    }

    private void getHeadImage(String remoteHeadImageFilePath) {
        if (Tools.isNullStr(remoteHeadImageFilePath)) {
            return;
        }

        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected void onPostExecute(Bitmap result) {
                if (result != null) {
                    String path = PathUtil.getElderAvatarPath(mContext
                            .getApplicationContext());
                    FileOutputStream out = null;
                    File parentAvatarFile = new File(path);
                    try {
                        out = new FileOutputStream(parentAvatarFile);
                        result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                        // your
                        // Bitmap
                        // instance
                        // PNG is a lossless format, the compression factor (100) is
                        // ignored
                        SharedPreferences prefs = mContext.getSharedPreferences(
                                Constant.USER_INFO, Context.MODE_PRIVATE);
                        Uri parentAvatarUri = Uri.fromFile(parentAvatarFile);
                        prefs.edit()
                                .putString(Constant.PARENT_AVATAR, parentAvatarUri.toString())
                                .apply();
                        setUserAvatar();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (out != null) {
                                out.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    if (mLeUser != null && mLeUser.callname != null) {
                        if (mLeUser.callname.contains("爸爸")
                                || mLeUser.callname.contains("爷爷")
                                || mLeUser.callname.contains("外公")) {
                            mHomeFaceImageView
                                    .setImageResource(R.drawable.defaut_parent_avtar_male);
                        } else {
                            mHomeFaceImageView
                                    .setImageResource(R.drawable.defaut_parent_avtar_female);
                        }
                    }
                }
            }

            @Override
            protected Bitmap doInBackground(String... urls) {
                String urldisplay = urls[0];
                Bitmap resultImage = null;
                URL url;
                try {
                    url = new URL(urldisplay);
                    HttpURLConnection urlConnection = (HttpURLConnection) url
                            .openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.connect();
                    InputStream in = urlConnection.getInputStream();
                    resultImage = BitmapFactory.decodeStream(in);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return resultImage;
            }
        }.execute(remoteHeadImageFilePath);

    }

    private void jump2Login() {
        Intent intent = new Intent();
        intent.setClass(mContext, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {

            case R.id.exitImg://退出小小金

                getActivity().finish();
                break;
            case R.id.rel_babykalaok:
                intent.setClass(mContext, BabyKaraokeActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_babytellstory:
                intent.setClass(mContext, BabyTellStoryActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_babycloudalbum:
                intent.setClass(mContext, BabyPhotoCloudActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_schoolalbum:// 校园相册
                intent.setClass(mContext, SchoolAlbumActivity.class);
                startActivity(intent);
                break;
            case R.id.rel_babyteacher:// 宝宝老师
                intent.setClass(mContext, AddTeacherListActivity.class);
                startActivity(intent);
                break;
            case R.id.scoreCenterLinearLayout:
                intent.putExtra("h5url", "http://weixin.jdy520.com/xxbjf/");
                intent.setClass(mContext, WebViewContainerActivity.class);
                startActivity(intent);
                break;
            case R.id.playHistoryLinearLayout:
                intent.setClass(mContext, RecentPlayActivity.class);
                startActivity(intent);
                break;
            case R.id.Mytopic: // 我的课程表
                intent = new Intent(getActivity(), BabyCalenderActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                break;
//    case R.id.MyDownloaded:
//      intent = new Intent(getActivity(), MyDownloadedActivity.class);
//      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//      startActivity(intent);
//      break;
            case R.id.device_stateview:
            case R.id.view_mydevice:
//      if (LeConfig.isLogin) {
                intent.setClass(mContext, DevicePropertyActivity.class);
                startActivity(intent);
//      } else {
//        intent.setClass(mContext, LoginActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        startActivity(intent);
//      }
                break;
            case R.id.img_setting:
                intent = new Intent(mContext, SettingActivity.class);
                startActivity(intent);
                break;
//    case R.id.Mymessage:
//      intent.setClass(mContext, MyMessageActivity.class);
//      startActivity(intent);
//      break;
            case R.id.Myvoice:
                if (LeXiaoXiaoBanApp.getInstance().getUser() == null) {
                    jump2Login();
                } else {
                    intent.setClass(mContext, MyVoiceActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.home_face_img: // 头像
                if (LeXiaoXiaoBanApp.getInstance().getUser() == null) {
                    jump2Login();
                } else {
                    intent.setClass(mContext, PersonalInformationActivity2.class);
                    startActivity(intent);
                }
                break;
            case R.id.Mylove:
//      if (LeXiaoXiaoBanApp.getInstance().getUser() == null) {
//        jump2Login();
//      } else {
                intent.setClass(mContext, MyLoveListActivity.class);
                startActivity(intent);
//      }
                break;
            case R.id.membershipPackageIntroLinearLayout:
                if (LeXiaoXiaoBanApp.getInstance().getUser() == null) {
                    jump2Login();
                } else {
                    intent.setClass(mContext, MembershipCenterActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
                break;

            case R.id.rel_story_baby:
                //宝宝故事机,跳转到故事机界面
                intent = new Intent(mContext, BreathLightActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void loadMessageData() {
        mSysMessageList = new ArrayList<LeSysMessage>();
        mSysMessageList.clear();

        if (mLeUser == null) {
            mLeUser = Tools.restoreLeUser();
        }

        Async
                .start(new Func0<ResponseResult>() {
                    @Override
                    public ResponseResult call() {

                        HashMap<String, Object> param_ = new HashMap<String, Object>();
                        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                        return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/member/message", param_, HttpUtils.TAG_GET_REQUEST);

                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new Func1<ResponseResult, Boolean>() {

                    @Override
                    public Boolean call(ResponseResult arg0) {

                        boolean r = (arg0 != null && Tools.isNotEmpty(arg0) && arg0
                                .isSuccess());
                        if (!r) {
                            // mBaseActivity.toastShow("获取系统信息失败");
                        }
                        return r;
                    }
                }).doOnCompleted(new Action0() {

            @Override
            public void call() {
                // if (mBaseActivity != null) {
                // mBaseActivity.dismissLoading();
                // }

                String str = LePreference.getInstance().getString("clickmymsg");

                if (mSysMessageList != null && !mSysMessageList.isEmpty()
                        && Tools.isEmpty(str)) {
                    // tv_unread.setText(mSysMessageList.size() + "");
                    // tv_unread.setVisibility(View.VISIBLE);
                } else {
                    // tv_unread.setVisibility(View.GONE);
                }
            }
        }).subscribe(new Action1<ResponseResult>() {
            @SuppressWarnings({"unchecked"})
            @Override
            public void call(ResponseResult arg0) {
                mSysMessageList = (List<LeSysMessage>) JsonSerializer.getInstance()
                        .deserialize(arg0.data, ArrayList.class, LeSysMessage.class);

            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {

            LeConfig.isInternetAvailable = Tools.isNetworkAvailable(getActivity());

            loadMessageData();
            setUserAvatar();

            if (!LeConfig.isDeviceConnect && device_stateview != null) {
                device_stateview.setPlaying(false);
            }

            if (!LeConfig.isInternetAvailable && device_stateview != null) {
                device_stateview.setPlaying(false);
            }

            LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
            LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();

            if (lu != null && username != null && lb != null) {
                if (Tools.isNotNullStr(lb)) {
                    username.setText(lb.name + "的" + lu.callname);
                } else {
                    username.setText(lu.nickname);
                }
            } else if (lu != null && username != null) {
                if (Tools.isNullStr(lu.machine)) {
                    username.setText("用户" + String.valueOf(lu.id));
                } else if (Tools.isNotNullStr(lu.machine)) {
                    username.setText(lu.machine.name + "的" + lu.callname);
                } else {
                    username.setText(lu.nickname);
                }
            }

            SocketThreadManager.getInstance().removeDataReceivedListener(TabMineFragment.this);
            SocketThreadManager.getInstance().setDataReceivedListener(TabMineFragment.this);


            SocketThreadManager.getInstance().removeDeviceStateListener(TabMineFragment.this);
            SocketThreadManager.getInstance().setDeviceStateListener(TabMineFragment.this);


            try {
                JSONObject dataJson = new JSONObject();
                dataJson.put("code", 202);
                dataJson.put("act", "machineinfo");
                SocketThreadManager.getInstance().send(dataJson.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }


            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", 202);
                        jsonObject.put("act", "videostatu");
                        SocketThreadManager.getInstance().send(jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 500);


        } else {
            // TODO
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        MobclickAgent.onPageStart(TAG);

        handler.removeMessages(1);
        handler.sendEmptyMessageDelayed(1, 5000);

        String str = LePreference.getInstance().getString("clickmymsg");

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();

        if (lu != null && username != null && lb != null) {
            if (Tools.isNotNullStr(lb)) {
                username.setText(lb.name + "的" + lu.callname);
            } else {
                username.setText(lu.nickname);
            }
        } else if (lu != null && username != null) {
            if (Tools.isNullStr(lu.machine)) {
                username.setText("用户" + String.valueOf(lu.id));
            } else if (Tools.isNotNullStr(lu.machine)) {
                username.setText(lu.machine.name + "的" + lu.callname);
            } else {
                username.setText(lu.nickname);
            }
        }

        setUserAvatar();
    }

    @Override
    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }

        unBind();

        try {
            if (mContext != null && mReceiver != null) {
                mContext.unregisterReceiver(mReceiver);
                mReceiver = null;
            }
        } catch (Exception e) {
        }

        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);

        handler.removeMessages(1);
    }

    private void doExitApp() {
        // clear cache
        LePreference.getInstance().delete(LePreference.PREFERNCE_TELLSTORY_CACHE);
        LePreference.getInstance().delete(LePreference.PREFERNCE_PUSHSTORY_CACHE);
        LePreference.getInstance().delete(LePreference.PREFERNCE_PUSHSLIDE_CACHE);
        LePreference.getInstance().delete(LePreference.PREFERNCE_SHARERANK_CACHE);
        LePreference.getInstance()
                .delete(LePreference.PREFERNCE_LAST_PUSHTIMESTAMP);
        LePreference.getInstance().delete(LePreference.PREFERNCE_NEXT_TIMESTAMP);
        LePreference.getInstance().delete("openradiodetailcount");
        LePreference.getInstance().delete("opensuitforbabydetailcount");

        LePreference.getInstance().delete("floatWindowVisibility");

        LePreference.getInstance().delete("playmode");

        Intent logoutIntent = new Intent("com.jdy.haoduoai.activity.logout");
        getActivity().sendBroadcast(logoutIntent);

        LeConfig.isLogin = false;
        LeConfig.isDeviceActivated = false;
        LeConfig.isDeviceBinded = false;
        LeConfig.isInfoFilled = false;
        // /Config.isReady = false;

        SocketThreadManager.getInstance().stopThreads();
        SocketThreadManager.getInstance().releaseInstance();

        File dir = getActivity().getFilesDir();
        File file1 = new File(dir, Constant.TELL_STORY_SERACH_FILE);
        file1.delete();
        File file2 = new File(dir, Constant.PUSH_STORY_SERACH_FILE);
        file2.delete();

        ACache pCache = ACache.get(getActivity());
        pCache.clear();

        LeXiaoXiaoBanApp.getInstance().forgetUser();

        Intent intent = new Intent(getActivity(), LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void unBind() {
        if (SocketThreadManager.getInstance() != null) {
            SocketThreadManager.getInstance().removeDeviceStateListener(TabMineFragment.this);
            SocketThreadManager.getInstance().removeDataReceivedListener(TabMineFragment.this);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * com.jdy.haoduoai.view.scrollview.OnScrollChangedCallback#onScroll(int,
     * int)
     */
    @Override
    public void onScroll(int l, int t, int oldl, int oldt) {
        // TODO Auto-generated method stub
        float newAlpha = (float) t / 500;

        int height = mScrollView.getHeight();
        int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
                .getMeasuredHeight();
        int dis = scrollViewMeasuredHeight - height;
        if (dis > 0) {
            newAlpha = (float) t / dis;
        }

        if (newAlpha >= 0.8 && newAlpha <= 1.0) {
            tv_name.setText("我的");
        } else {
            tv_name.setText("");
        }

        mHeadImg.setAlpha(1.0f * newAlpha);
    }

    @Override
    public void onRemoteLogin() {
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                device_stateview.setPlaying(false);
            }
        });

    }

    @Override
    public void onConnectionChanged(boolean connect) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPowerChanged(int power) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(int updatingStatus) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCheckDeviceVersion(String version) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPlayNextFailed() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPlayPrevFailed() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPlayMedia(final PlayState playState, MediaType type,
                            JSONObject data) {
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (playState.equals(PlayState.Playing)) {
                    device_stateview.setPlaying(true);
                } else {
                    device_stateview.setPlaying(false);
                }

            }
        });
    }

    @Override
    public void onReceivedVoiceMessage(String streamUrl) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDataReceived(String data) {
        // TODO Auto-generated method stub

    }
}
